package com.mingzhi.lotterysystem.service.impl;

import com.mingzhi.lotterysystem.common.errorcode.ServiceErrorCodeConstants;
import com.mingzhi.lotterysystem.common.exception.ServiceException;
import com.mingzhi.lotterysystem.common.pojo.CommonResult;
import com.mingzhi.lotterysystem.common.utils.JacksonUtil;
import com.mingzhi.lotterysystem.common.utils.RedisUtil;
import com.mingzhi.lotterysystem.controller.param.CreateActivityParam;
import com.mingzhi.lotterysystem.controller.param.CreatePrizeByActivityParam;
import com.mingzhi.lotterysystem.controller.param.CreateUserByActivityParam;
import com.mingzhi.lotterysystem.controller.param.PageParam;
import com.mingzhi.lotterysystem.dao.dataobject.ActivityDO;
import com.mingzhi.lotterysystem.dao.dataobject.ActivityPrizeDO;
import com.mingzhi.lotterysystem.dao.dataobject.ActivityUserDO;
import com.mingzhi.lotterysystem.dao.dataobject.PrizeDO;
import com.mingzhi.lotterysystem.dao.mapper.*;
import com.mingzhi.lotterysystem.service.ActivityService;
import com.mingzhi.lotterysystem.service.dto.ActivityDTO;
import com.mingzhi.lotterysystem.service.dto.ActivityDetailDTO;
import com.mingzhi.lotterysystem.service.dto.CreateActivityDTO;
import com.mingzhi.lotterysystem.service.dto.PageListDTO;
import com.mingzhi.lotterysystem.service.enums.ActivityPrizeStatusEnum;
import com.mingzhi.lotterysystem.service.enums.ActivityPrizeTiersEnum;
import com.mingzhi.lotterysystem.service.enums.ActivityStatusEnum;
import com.mingzhi.lotterysystem.service.enums.ActivityUserStatusEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Service
public class ActivityServiceImpl implements ActivityService {

    private static final Logger logger = LoggerFactory.getLogger(ActivityServiceImpl.class);

    /**
     * 活动缓存前缀 为了区分业务
     */
    private final String ACTIVITY_PREFIX = "ACTIVITY_";

    /**
     * 活动缓存过期时间 最小单位 s
     */
    private final Long ACTIVITY_TIMEOUT = 60 * 60 * 24 * 3L;

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private PrizeMapper prizeMapper;
    @Autowired
    private ActivityMapper activityMapper;
    @Autowired
    private ActivityPrizeMapper activityPrizeMapper;
    @Autowired
    private ActivityUserMapper activityUserMapper;
    @Autowired
    private RedisUtil redisUtil;


    /**
     * 这里牵扯到同时多表存放信息，要考虑到事务处理
     *
     * @param param
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)//如果抛异常就回滚
    public CreateActivityDTO createActivity(CreateActivityParam param) {
        //进行校验（主要是活动奖品的数量等）
        checkActivityInfo(param);

        //保存基本活动信息
        ActivityDO activityDO = new ActivityDO();
        activityDO.setActivityName(param.getActivityName());
        activityDO.setDescription(param.getDescription());
        activityDO.setStatus(ActivityStatusEnum.RUNNING.name());
        activityMapper.insert(activityDO);

        //保存活动关联的奖品信息
        List<CreatePrizeByActivityParam> prizeParams = param.getActivityPrizeList();
        List<ActivityPrizeDO> activityPrizeDOList = prizeParams.stream()
                .map(prizeParam -> {
                    ActivityPrizeDO activityPrizeDO = new ActivityPrizeDO();
                    activityPrizeDO.setActivityId(activityDO.getId());
                    activityPrizeDO.setPrizeId(prizeParam.getPrizeId());
                    activityPrizeDO.setPrizeAmount(prizeParam.getPrizeAmount());
                    activityPrizeDO.setPrizeTiers(prizeParam.getPrizeTiers());
                    activityPrizeDO.setStatus(ActivityPrizeStatusEnum.INIT.name());
                    return activityPrizeDO;
                }).collect(Collectors.toList());
        Integer i = activityPrizeMapper.batchInsert(activityPrizeDOList);

        //保存活动关联的人员信息
        List<CreateUserByActivityParam> userParams = param.getActivityUserList();
        List<ActivityUserDO> activityUserDOList = userParams.stream()
                .map(userParam -> {
                    ActivityUserDO activityUserDO = new ActivityUserDO();
                    activityUserDO.setActivityId(activityDO.getId());
                    activityUserDO.setUserId(userParam.getUserId());
                    activityUserDO.setUserName(userParam.getUserName());
                    activityUserDO.setStatus(ActivityUserStatusEnum.INIT.name());
                    return activityUserDO;
                }).collect(Collectors.toList());
        Integer i1 = activityUserMapper.batchInsert(activityUserDOList);

        //整合完整的活动信息，将其存放在redis中
        // 活动详情 ActivityDetailDTO : 活动 + 奖品 + 人员
        //根据 activityId 查询
        //先获取奖品基本属性列表
        //获取需要查询的奖品id
        List<Long> prizeIds = param.getActivityPrizeList().stream()
                .map(CreatePrizeByActivityParam::getPrizeId)
                .distinct()
                .collect(Collectors.toList());
        List<PrizeDO> prizeDOList = prizeMapper.batchSelectByIds(prizeIds);
        ActivityDetailDTO detailDTO = convertToActivityDetailDTO(
                activityDO, activityUserDOList, prizeDOList, activityPrizeDOList);

        cacheActivity(detailDTO);
        //构造返回
        CreateActivityDTO createActivityDTO = new CreateActivityDTO();
        createActivityDTO.setActivityId(activityDO.getId());
        return createActivityDTO;
    }

    /**
     * 缓存完整的活动信息  ActivityDetailDTO
     *
     * @param detailDTO
     */
    private void cacheActivity(ActivityDetailDTO detailDTO) {
        //约定 redis 中 key 为 ACTIVITY_activityId
        //value ： ActivityDetailDTO(json)

        //进行判断
        if (null == detailDTO || null == detailDTO.getActivityId()) {
            logger.warn("要缓存的活动信息不存在");
            return;
        }
        //捕获一下异常
        try {
            String key = ACTIVITY_PREFIX + detailDTO.getActivityId();
            String value = JacksonUtil.writeValueAsString(detailDTO);
            redisUtil.set(key, value, ACTIVITY_TIMEOUT);
        } catch (Exception e) {
            logger.warn("缓存活动异常，ActivityDetailDTO = {}", JacksonUtil.writeValueAsString(detailDTO), e);
        }
    }

    /**
     * 从Redis缓存中获取数据
     *
     * @param activityId
     * @return
     */
    public ActivityDetailDTO getActivityFromCache(Long activityId) {
        if (null == activityId) {
            logger.warn("获取缓存活动数据的activityId为空！");
            return null;
        }
        try {
            String str = redisUtil.get(ACTIVITY_PREFIX + activityId);
            if (!StringUtils.hasText(str)) {
                logger.info("获取缓存活动数据为空！key = {}", ACTIVITY_PREFIX + activityId);
                return null;
            }
            return JacksonUtil.readValue(str, ActivityDetailDTO.class);
        } catch (Exception e) {
            logger.error("从缓存中获取活动信息异常,key = {}", ACTIVITY_PREFIX + activityId, e);
            return null;
        }
    }

    /**
     * 根据基本DO整合完整的活动信息ActivityDetailDTO
     *
     * @param activityDO
     * @param activityUserDOList
     * @param prizeDOList
     * @param activityPrizeDOList
     * @return
     */
    private ActivityDetailDTO convertToActivityDetailDTO(ActivityDO activityDO,
                                                         List<ActivityUserDO> activityUserDOList,
                                                         List<PrizeDO> prizeDOList,
                                                         List<ActivityPrizeDO> activityPrizeDOList) {
        ActivityDetailDTO detailDTO = new ActivityDetailDTO();
        detailDTO.setActivityId(activityDO.getId());
        detailDTO.setActivityName(activityDO.getActivityName());
        detailDTO.setDesc(activityDO.getDescription());
        detailDTO.setStatus(ActivityStatusEnum.forName(activityDO.getStatus()));

        // apDO: {prizeId，amount, status}, {prizeId，amount, status}
        // pDO: {prizeid, name....},{prizeid, name....},{prizeid, name....}
        List<ActivityDetailDTO.PrizeDTO> prizeDTOList = activityPrizeDOList
                .stream()
                .map(apDO -> {
                    ActivityDetailDTO.PrizeDTO prizeDTO = new ActivityDetailDTO.PrizeDTO();
                    prizeDTO.setPrizeId(apDO.getPrizeId());
                    Optional<PrizeDO> optionalPrizeDO = prizeDOList.stream()
                            .filter(prizeDO -> prizeDO.getId().equals(apDO.getPrizeId()))
                            .findFirst();
                    // 如果PrizeDO为空，不执行当前方法，不为空才执行
                    optionalPrizeDO.ifPresent(prizeDO -> {
                        prizeDTO.setName(prizeDO.getName());
                        prizeDTO.setImageUrl(prizeDO.getImageUrl());
                        prizeDTO.setPrice(prizeDO.getPrice());
                        prizeDTO.setDescription(prizeDO.getDescription());
                    });
                    prizeDTO.setTiers(ActivityPrizeTiersEnum.forName(apDO.getPrizeTiers()));
                    prizeDTO.setPrizeAmount(apDO.getPrizeAmount());
                    prizeDTO.setStatus(ActivityPrizeStatusEnum.forName(apDO.getStatus()));
                    return prizeDTO;
                }).collect(Collectors.toList());
        detailDTO.setPrizeDTOList(prizeDTOList);

        List<ActivityDetailDTO.UserDTO> userDTOList = activityUserDOList.stream()
                .map(auDO -> {
                    ActivityDetailDTO.UserDTO userDTO = new ActivityDetailDTO.UserDTO();
                    userDTO.setUserId(auDO.getUserId());
                    userDTO.setUserName(auDO.getUserName());
                    userDTO.setStatus(ActivityUserStatusEnum.forName(auDO.getStatus()));
                    return userDTO;
                }).collect(Collectors.toList());
        detailDTO.setUserDTOList(userDTOList);
        return detailDTO;
    }

    /**
     * 校验活动的有效性
     *
     * @param param
     */
    private void checkActivityInfo(CreateActivityParam param) {
        //在进行一次判断
        //因为service 与 controller 两层进行了解耦，加一层判断更好
        if (null == param) {
            throw new ServiceException(ServiceErrorCodeConstants.CREATE_ACTIVITY_INFO_IS_EMPTY);
        }

        //首先判断人员id在人员列表是否存在 （全部 id 一起判断）
        /**
         * Java 中 Stream API 的使用
         * 它从 param.getActivityUserList() 中提取用户 ID
         * 去重并最终转换为一个 List<Long> 类型的列表
         */
        List<Long> userIds = param.getActivityUserList()
                .stream()
                //map 是流操作中的一个中间操作
                //它接受一个 Function 类型的参数，作用是将流中的每个元素转换成另外一种形式。
                .map(CreateUserByActivityParam::getUserId)
                .distinct()//去重
                .collect(Collectors.toList());
        List<Long> existUserIds = userMapper.selectExistByIds(userIds);
        //如果 existUserIds 为空的话， existUserIds.contains(id) 就会抛异常
        //这里要进行处理
        if (CollectionUtils.isEmpty(existUserIds)) {
            //既然这个都为空，说明人员id在人员表中不存在，直接抛异常
            throw new ServiceException(ServiceErrorCodeConstants.ACTIVITY_USER_ERROR);
        }
        userIds.forEach(id -> {
            if (!existUserIds.contains(id)) {
                throw new ServiceException(ServiceErrorCodeConstants.ACTIVITY_USER_ERROR);
            }
        });

        //再判断奖品id在奖品列表是否存在
        List<Long> prizeIds = param.getActivityPrizeList()
                .stream()
                //map 是流操作中的一个中间操作
                //它接受一个 Function 类型的参数，作用是将流中的每个元素转换成另外一种形式。
                .map(CreatePrizeByActivityParam::getPrizeId)
                .distinct()//去重
                .collect(Collectors.toList());
        List<Long> existPrizeIds = prizeMapper.selectExistByIds(prizeIds);
        if (CollectionUtils.isEmpty(existPrizeIds)) {
            throw new ServiceException(ServiceErrorCodeConstants.ACTIVITY_PRIZE_ERROR);
        }
        prizeIds.forEach(id -> {
            if (!existPrizeIds.contains(id)) {
                throw new ServiceException(ServiceErrorCodeConstants.ACTIVITY_PRIZE_ERROR);
            }
        });

        //人员数量要大于等于奖品数量
        Integer userAmount = param.getActivityUserList().size();
        Long prizeAmount = param.getActivityPrizeList()
                .stream()
                .mapToLong(CreatePrizeByActivityParam::getPrizeAmount)
                .sum();
        if (userAmount < prizeAmount) {
            throw new ServiceException(ServiceErrorCodeConstants.USER_PRIZE_AMOUNT_ERROR);
        }

        //校验活动奖品等级有效性
        param.getActivityPrizeList().forEach(prize -> {
            if (null == ActivityPrizeTiersEnum.forName(prize.getPrizeTiers())) {
                throw new ServiceException(ServiceErrorCodeConstants.ACTIVITY_PRIZE_TIERS_ERROR);
            }
        });
    }

    @Override
    public PageListDTO<ActivityDTO> findActivityList(PageParam param) {
        //获取总量
        Integer total = activityMapper.count();

        //获取当前列表
        List<ActivityDO> activityDOList = activityMapper.selectActivityList(param.offset(),param.getPageSize());
        List<ActivityDTO> activityDTOList = activityDOList.stream()
                .map(activityDO -> {
                    ActivityDTO activityDTO = new ActivityDTO();
                    activityDTO.setActivityId(activityDO.getId());
                    activityDTO.setActivityName(activityDO.getActivityName());
                    activityDTO.setDescription(activityDO.getDescription());
                    activityDTO.setStatus(ActivityStatusEnum.forName(activityDO.getStatus()));
                    return activityDTO;
                }).collect(Collectors.toList());
        return new PageListDTO<>(total,activityDTOList);
    }

    @Override
    public ActivityDetailDTO getActivityDetail(Long activityId) {
        //先从 redis 中进行查取
        if (null == activityId) {
            logger.warn("查询活动详细信息失败，activityId为空！");
            return null;
        }
        ActivityDetailDTO detailDTO = getActivityFromCache(activityId);
        if(null != detailDTO){
            logger.info("查询活动详细信息成功！detailDTO = {}",JacksonUtil.writeValueAsString(detailDTO));
            return detailDTO;
        }
        //如果redis 中不存在，查表
        //活动表
        ActivityDO aDO = activityMapper.selectActivityId(activityId);

        //活动奖品表
        List<ActivityPrizeDO> apDOList = activityPrizeMapper.selectByActivityId(activityId);

        //活动人员表
        List<ActivityUserDO> auDOList = activityUserMapper.selectByActivityId(activityId);

        //奖品表
        //先获取该活动中奖品的id
        List<Long> prizeIds = apDOList.stream()
                .map(ActivityPrizeDO::getPrizeId)
                .collect(Collectors.toList());
        //进行查询
        List<PrizeDO> pDOList = prizeMapper.batchSelectByIds(prizeIds);

        //整合活动详细信息，存放在redis中
        detailDTO = convertToActivityDetailDTO(aDO, auDOList, pDOList, apDOList);
        cacheActivity(detailDTO);
        //返回
        return detailDTO;
    }

    @Override
    public void cacheActivity(Long activityId) {
        //1.查询表数据
        //活动表
        //活动奖品关联表
        //活动人员关联表
        //奖品信息表
        //整合并缓存
        if(null == activityId){
            logger.warn("要缓存的id为空！");
            throw new ServiceException(ServiceErrorCodeConstants.CACHE_ACTIVITY_ID_IS_EMPTY);
        }
        //活动表
        ActivityDO aDO = activityMapper.selectActivityId(activityId);
        if(null == aDO){
            logger.error("要缓存的活动id有误！");
            throw new ServiceException(ServiceErrorCodeConstants.CACHE_ACTIVITY_ID_ERROR);
        }

        //活动奖品表
        List<ActivityPrizeDO> apDOList = activityPrizeMapper.selectByActivityId(activityId);

        //活动人员表
        List<ActivityUserDO> auDOList = activityUserMapper.selectByActivityId(activityId);

        //奖品表
        //先获取该活动中奖品的id
        List<Long> prizeIds = apDOList.stream()
                .map(ActivityPrizeDO::getPrizeId)
                .collect(Collectors.toList());
        //进行查询
        List<PrizeDO> pDOList = prizeMapper.batchSelectByIds(prizeIds);

        //整合活动详细信息，存放在redis中
        cacheActivity(convertToActivityDetailDTO(aDO, auDOList, pDOList, apDOList));
    }
}
